package com.yskj.mwk.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class WenZi2Pic {
    public static void main(String[] args) {
        String modelPath = "D:\\368760.jpg";
        String sourcePath = "D:\\source1.png";
        String savePath = "D:\\result1.png";
        savePic("皮卡丘，你准备好与我并肩作战，共同征服这个世界了吗？",modelPath,sourcePath,savePath);
    }


    public static void savePic(String text,String modelPath,String sourcePath,String savePath){
        try {
            //新建图片或者导入模版图片
//            BufferedImage bufImage = createImage(100,200,1);
//            g.setColor(new Color(0xDCDCDC));
//            g.setColor(Color.WHITE);
//            g.fillRect(0,0,srcImgWidth,srcImgHeight);

            BufferedImage bufImage = ImageIO.read(new File(modelPath));

            BufferedImage imageNew = new BufferedImage(bufImage.getWidth(), bufImage.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = imageNew.createGraphics();
            g.drawImage(bufImage, 0, 0, bufImage.getWidth(), bufImage.getHeight(), null);
            //字体的平滑处理
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            //设置输出字体
            Font font = new Font("楷体", Font.BOLD, 50);
            g.setFont(font);
            g.setColor(Color.BLACK);
            //写字，注意：输入的坐标为第一个字左下角坐标
            g.drawString(text, 20, 500);
            //添加图片
            BufferedImage headImage = ImageIO.read(new File(sourcePath));
            g.drawImage(headImage,500, 600,null);
            g.dispose();
            //保存图片
            OutputStream fos = new FileOutputStream(savePath);
            ImageIO.write(imageNew, "png", fos);
            bufImage.flush();
            imageNew.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新建图片
     *
     * @param width     图片宽
     * @param height    图片高
     * @param imageType 图片类型
     * @return 图片实体
     */
    private static BufferedImage createImage(int width, int height, int imageType) {
        // 新建图片
        return new BufferedImage(width, height, imageType);
    }

    /**
     * 绘制背景
     * @param image    画布
     * @param graphics 画笔
     * @param bgColor  背景颜色
     */
    private static void fillBackground(BufferedImage image, Graphics graphics, Color bgColor) {
        int width = image.getWidth();
        int height = image.getHeight();
        graphics.setClip(0, 0, width, height);
        // 设置画笔颜色
        graphics.setColor(bgColor);
        // 绘制背景
        graphics.fillRect(0, 0, width, height);
    }
}
